package com.gyt.manager.test;

import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * synchronized和锁，两者中，前者实现同步，后者为同步的线程提供锁。
 *
 * @author gyt created on 2021/5/19 21:53
 **/
@Slf4j
public class SalleTicket implements Runnable {
    private int tickets = 100;
    private int count = 0;

    private static Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
//            lock.lock();
            synchronized (this) {
                if (tickets > 0) {
                    try {
                        Thread.sleep(new Random().nextInt(200));
                    } catch (InterruptedException e) {
                        log.error("error", e);
                    }
                    tickets--;
                    count++;
                    System.out.println(
                            Thread.currentThread().getName() +
                                    "售出了第" + (count) + "张票");
                }
            }
//            lock.unlock();
        }
    }

    public static void main(String[] args) {
        SalleTicket st = new SalleTicket();
        SalleTicket st2 = new SalleTicket();
        Thread t1 = new Thread(st, "窗口1");
        Thread t2 = new Thread(st, "窗口2");
        Thread t3 = new Thread(st, "窗口3");
        Thread t4 = new Thread(st, "窗口4");
        t1.start();
        t2.start();
        t3.start();
        t4.start();

    }
}
